﻿////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// <copyright>Copyright 2008-2011 Andreas Huber Doenni</copyright>
// Distributed under the Microsoft Public License (Ms-PL).
// See accompanying file License.txt or copy at http://mews.codeplex.com/license.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

namespace Mews.Net.Nntp.Cache
{
    using System;

    /// <summary>The base class of all classes, the objects of which are unambiguously identifiable with an
    /// <see cref="int"/> identifier.</summary>
    /// <typeparam name="TDerived">The internal subclass of this type.</typeparam>
    /// <typeparam name="TInterface">The public interface the subclass implements.</typeparam>
    internal abstract class IntIdObject<TDerived, TInterface> : IEquatable<TInterface>
        where TDerived : IntIdObject<TDerived, TInterface>, TInterface
        where TInterface : IEquatable<TInterface>
    {
        private readonly int id;

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        /// <summary>See <see cref="IEquatable{T}.Equals"/>.</summary>
        public bool Equals(TInterface other)
        {
            return this.Equals(other as TDerived);
        }

        /// <summary>See <see cref="object.Equals(object)"/>.</summary>
        public sealed override bool Equals(object obj)
        {
            return this.Equals(obj as TDerived);
        }

        /// <summary>See <see cref="object.GetHashCode"/>.</summary>
        public sealed override int GetHashCode()
        {
            return this.id;
        }

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        internal int Id
        {
            get { return this.id; }
        }

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        /// <summary>Initializes a new instance of the <see cref="IntIdObject{TDerived, TInterface}"/> class.</summary>
        /// <param name="id">The value that unambiguously identifies this object.</param>
        protected IntIdObject(int id)
        {
            this.id = id;
        }

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        private bool Equals(TDerived other)
        {
            return (other != null) && (other.id == this.id);
        }
    }
}
